import React, { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Flex, message, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import Cloud from 'leancloud-storage'
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

// 3. 接收图片文件资源对象，将其转换为base64编码，通过callback返回给调用者
const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

// 1. 上传前对文件类型、文件大小做判断
const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
interface PropType{
  onChange?:(url:string)=>void,
  value?:string
}
const ImgUpload: React.FC<PropType> = (props) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(); //存储图片预览链接
  console.log('Form给ImgUpload传递的props',props);
  
  //2. 自定义图片上传方法
  const handleUpload = (info:any)=>{
    console.log(info);
    getBase64(info.file,(base64:string)=>{
      console.log(base64);
      const leanCloudFile = new Cloud.File('student_avatar.png',{base64}) //将本地图片资源转为leancloud资源
      leanCloudFile.save().then((res:any)=>{ //上传图片
        console.log(res);
        let {url} = res.attributes
        props.onChange!(url) //将图片链接设置给Form表单元素
        setImageUrl(url) //预览在线图片链接
      })
      // setImageUrl(base64)  //测试base64可用性
    })
    
  }

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>图片上传</div>
    </button>
  );

  return (
    <Flex gap="middle" wrap>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={handleUpload}
      >
        {imageUrl||props.value ? <img src={imageUrl||props.value} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    </Flex>
  );
};

export default ImgUpload;